package com.hospital.insurancepeople.module.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hospital.api.RemoteEndesctryptionService;
import com.hospital.common.core.module.entity.NFC.NFCResponse;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.DateUtil;
import com.hospital.insurancepeople.async.WxPayFunc;
import com.hospital.insurancepeople.module.entity.InsuranceLogs;
import com.hospital.insurancepeople.module.entity.SettleRequestEntity;
import com.hospital.insurancepeople.module.entity.WxPayEntity;
import com.hospital.insurancepeople.module.mapper.InsuranceLogsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * prepayin
 *
 * @description 接口转调
 * @author:louislau
 * @create 2019-11-08 08:56:25
 **/

@RestController
@RequestMapping("/info")
@Slf4j
public class InfoTransfer {

    @Autowired
    private WxPayFunc wxPayFunc;

    @Resource
    private InsuranceLogsMapper insuranceLogsMapper;

    @Resource
    private RemoteEndesctryptionService endesctryptionService;

    @Resource
    private RestTemplate restTemplate;


//        private String endesUrl = "http://192.168.20.42:8097/enctrytion/insurance";
//    private String endesUrl = "http://192.168.13.230:8097/enctrytion/insurance";

    /**
     * 柜面第三方支付
     *
     * @param params
     * @return
     */
    @RequestMapping("/wxPay")
    public Tip wxPayTransfer(@RequestBody String params) {
        WxPayEntity wxPayEntity = JSON.parseObject(params, WxPayEntity.class);
        if (wxPayEntity == null || wxPayEntity.getOrderClass() == null || wxPayEntity.getOrderClass().equals("")) {
            SettleRequestEntity settleRequestEntity = JSON.parseObject(params, SettleRequestEntity.class);
            if (settleRequestEntity == null || settleRequestEntity.getSettlePatientInfo() == null || settleRequestEntity.getSettlePatientInfo().size() <= 0) {
                log.error("无充值数据====================请求参数：" + JSON.toJSONString(params));
                return new ErrorTip(1001, "无充值数据");
            }
            wxPayEntity = settleRequestEntity.getSettlePatientInfo().get(0);
        }
//        wxPayFunc.wxPay(wxPayEntity);
        return new SuccessTip("已执行");
    }

    @RequestMapping("/sendPeople")
    public Tip wxPayTransfer(@RequestBody String params, HttpServletResponse httpServletResponse) throws InterruptedException {
        JSONObject jsonObject = JSON.parseObject(params);
        JSONArray data = jsonObject.getJSONArray("data");
        String tableName = jsonObject.getString("tableName");
        String action = jsonObject.getString("action");
        String endesUrl = insuranceLogsMapper.getEncryptionUrl();
        if (!action.equals("DELETE")) {
            for (Object jsonObject1 : data) {
                String uploadDate = JSON.parseObject(jsonObject1.toString()).getString("UPLOAD_DATE");
                String serialNo = JSON.parseObject(jsonObject1.toString()).getString("SERIAL_NO");
                //通过配置地址查看是否转发
                String url = insuranceLogsMapper.selectUrl(serialNo
                        + "_URL");
                if (!Objects.isNull(url)) {
                    //因表中无主键，因此根据查询条件查出几条就推送
                    QueryWrapper<InsuranceLogs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.apply(" SERIAL_NO = {0} " +
                            "and UPLOAD_DATE =to_date({1},'yyyy-mm-dd hh24:mi:ss')", serialNo, uploadDate);
                    List<InsuranceLogs> insuranceLogsList = insuranceLogsMapper.
                            selectList(queryWrapper);
                    if (!Objects.isNull(insuranceLogsList)) {
                        for (InsuranceLogs insuranceLogs : insuranceLogsList) {
                            NFCResponse nfcResponse = new NFCResponse();
                            nfcResponse.setEncData("");
                            nfcResponse.setAppId("1G00VOLSP0143F60C80A00005F9F40EF");
                            String insuranceJson = insuranceLogs.getInsuranceJson();
                            Object parse = JSON.parse(insuranceJson);
                            JSONObject jsonObjectInput = JSON.parseObject(parse.toString());
                            nfcResponse.setData(jsonObjectInput.get("input"));
//                            nfcResponse.setUrl(endesUrl);
                            nfcResponse.setSignType("SM3");
                          String printLog = "\r\n传输数据:" + data + "\r\ntableName:" + tableName +
                                    "\r\naction:" + action +
                                    "\r\ninfo:" + insuranceLogs.getSerialNo() +
                                    "\r\nupload_date:"+ DateUtil.format(insuranceLogs.getUploadDate(),"yyyy-MM-dd HH:mm:ss") +
                                    "\r\npatient_id:" + insuranceLogs.getPatientId()
                                    + "\r\nvisit_id:" + insuranceLogs.getVisitId();
                            printLog = printLog + "\r\n人保加密接口入参："+ JSON.toJSONString(nfcResponse);
                            Tip mapEnc = JSONObject.parseObject(endesctryptionService.getEncDesc(nfcResponse),Tip.class);
                            if (mapEnc.getCode()==200){
                                String enc =JSONObject.toJSONString(mapEnc.getData());
                                printLog = printLog + "\r\n人保加密接口出参、人保推送入参：" + enc + "\r\n推送描述:加密执行成功!";
                                if (enc != null) {
                                    wxPayFunc.wxPay(enc, url, printLog,restTemplate);
                                }
                            }else {
                                printLog = printLog + "\r\n推送描述:加密执行失败!" +mapEnc.getMessage();
                                log.info(printLog);
                            }
                        }
                    }
                }

            }
        }
        return new SuccessTip("已执行");
    }


}
